﻿using Client.Constant;
using Client.Enum;
using Client.Framework.Event;
using Client.Framework.Message;
using Client.Framework.Socket;
using Client.Message.Request;
using Client.Message.Response;
using Client.Model;
using Client.Service;
using Client.View;
using Client.View.RoleView;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;
using SuperSocket.ClientEngine.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Client.ViewModel
{
    public class RoleManagePageViewModel : BindableBase
    {
        public RoleManagePageViewModel()
        {
            MsgEventSubscribe();
            Init();
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private void Init() {
            AddRoleCommand = new DelegateCommand(AddRole);
            RefreshRoleListCommand = new DelegateCommand(RefreshRoleList);
            PrePageCommand = new DelegateCommand(PrePage);
            NextPageCommand = new DelegateCommand(NextPage);
            EditRoleCommand = new DelegateCommand<ViewRole>(EditRole);
            DeleteRoleCommand = new DelegateCommand<ViewRole>(DeleteRole);
            AllotPerRoleCommand = new DelegateCommand<ViewRole>(AllotPerRole);
            RoleEditWindow = new RoleEdit();

            SearchCommand = new DelegateCommand(Search);
            ResetCommand = new DelegateCommand(Reset);

            HasPrePage = false;
            HasNextPage = false;

            // 获取菜单树
            InitRoles();
        }

        private void MsgEventSubscribe()
        {
            MessageEventPublisher.SubscribeEvent(MessageId.ROLE_LIST, RolesResp);
            MessageEventPublisher.SubscribeEvent(MessageId.OPT_RESP, ReceiveOptMsg);
            MessageEventPublisher.SubscribeEvent(MessageId.RESPONSE_MENUS_TREE, MenusTreeResponse);
        }


        public void InitRoles()
        {
            GetRoles();
        }

        private List<MainMenu> menus;

        public List<MainMenu> Menus
        {
            get { return menus; }
            set
            {
                menus = value;
                RaisePropertyChanged("Menus");
            }
        }



        /// <summary>
        /// 新增编辑页面
        /// </summary>
        public RoleEdit RoleEditWindow { get; private set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        private int currentPage = 1;

        public int CurrentPage
        {
            get { return currentPage; }
            set { currentPage = value; RaisePropertyChanged("CurrentPage"); }
        }

        /// <summary>
        /// 每页条数
        /// </summary>
        private readonly int LIMIT = 10;

        /// <summary>
        /// 是否有上一页
        /// </summary>
        private bool hasPrePage;

        public bool HasPrePage
        {
            get { return hasPrePage; }
            set
            {
                hasPrePage = value;
                RaisePropertyChanged("HasPrePage");
            }
        }



        /// <summary>
        /// 是否有下一页
        /// </summary>
        private bool hasNextPage;

        public bool HasNextPage
        {
            get { return hasNextPage; }
            set
            {
                hasNextPage = value;
                RaisePropertyChanged("HasNextPage");
            }
        }



        /// <summary>
        /// 角色列表
        /// </summary>
        private List<ViewRole> roles;

        public List<ViewRole> Roles
        {
            get { return roles; }
            set
            {
                roles = value;
                RaisePropertyChanged("Roles");
            }
        }


        /// <summary>
        /// 新增角色
        /// </summary>
        public DelegateCommand AddRoleCommand { get; private set; }
        public void AddRole()
        {
            RoleEditWindow.BindRole(this);
            RoleEditWindow.ShowDialog();
        }

        /// <summary>
        /// 刷新角色列表
        /// </summary>
        public DelegateCommand RefreshRoleListCommand { get; private set; }
        public void RefreshRoleList()
        {
            GetRoles();
        }

        /// <summary>
        /// 上一页
        /// </summary>
        public DelegateCommand PrePageCommand { get; private set; }
        public void PrePage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                GetRoles();
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        public DelegateCommand NextPageCommand { get; private set; }
        public void NextPage()
        {
            CurrentPage++;
            GetRoles();
        }

        /// <summary>
        /// 编辑角色信息
        /// </summary>
        public DelegateCommand<ViewRole> EditRoleCommand { get; private set; }
        public void EditRole(ViewRole role)
        {
            RoleEditWindow.BindRole(this, role);
            RoleEditWindow.ShowDialog();
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        public DelegateCommand<ViewRole> DeleteRoleCommand { get; private set; }
        private int deleteRoleId;
        public void DeleteRole(ViewRole role)
        {
            this.deleteRoleId = role.ID;
            CancelConfirmTip tip = new CancelConfirmTip()
            {
                Message = { Text = $"确定删除角色{role.RoleName}吗？" }
            };
            DialogHost.Show(tip, "MainPanel", CloseTip);
        }

        public void CloseTip(object sender, DialogClosingEventArgs eventArgs)
        {
            if (string.Equals(eventArgs.Parameter, "Cancel")) return;
            DeleteRoleReq msg = new DeleteRoleReq(MessageId.DELETE_ROLE)
            {
                ID = this.deleteRoleId
            };
            ApplicationClient.Instance().Send(msg);
        }


        /// <summary>
        /// 编辑角色权限
        /// </summary>
        public DelegateCommand<ViewRole> AllotPerRoleCommand { get; private set; }
        public void AllotPerRole(ViewRole role)
        {
            GetMenusTree(role.ID);
            SelectedAllotPerRole = role;
        }
        // 选中的要分配权限角色
        public ViewRole SelectedAllotPerRole { get; set; }

        public void ConfirmAllotPer(object sender, DialogClosingEventArgs eventArgs)
        {
            if (Equals(eventArgs.Parameter, "Cancel"))
            {
                return;
            }
            AllotPerReq msg = new AllotPerReq(MessageId.REQUEST_ALLOT_PERMISSION)
            {
                RoleId = SelectedAllotPerRole.ID
            };
            MainMenus.ForEach(mainMenu =>
            {
                AllotMenu allotMenu = new AllotMenu();
                allotMenu.MenuId = mainMenu.ID;
                if (mainMenu.Checked == true)
                {
                    allotMenu.CheckedType = 1;
                }
                else if (mainMenu.Checked == false)
                {
                    allotMenu.CheckedType = 2;
                }
                else if (mainMenu.Checked == null)
                {
                    allotMenu.CheckedType = 3;
                }
                msg.AllotMenuList.Add(allotMenu);
                mainMenu.SubMenus.ForEach(subMenu =>
                {
                    AllotMenu allotSubMenu = new AllotMenu();
                    allotSubMenu.MenuId = subMenu.ID;
                    if (subMenu.Checked == true)
                    {
                        allotSubMenu.CheckedType = 1;
                    }
                    else if (subMenu.Checked == false)
                    {
                        allotSubMenu.CheckedType = 2;
                    }
                    else if (subMenu.Checked == null)
                    {
                        allotSubMenu.CheckedType = 3;
                    }
                    msg.AllotMenuList.Add(allotSubMenu);
                });
            });
            ApplicationClient.Instance().Send(msg);
        }

        public AllotPermission AllotPerPage { get; set; }
        private void GetMenusTree(int roleId)
        {
            MenusTreeReq msg = new MenusTreeReq(MessageId.REQUEST_MENUS_TREE)
            {
                IsAll = 1,
                RoleId = roleId
            };
            ApplicationClient.Instance().Send(msg);
        }

        public List<MainMenu> MainMenus { get; set; }
        private void MenusTreeResponse(ResponseBaseMessage message)
        {
            if (message is MenusTreeResp msg)
            {
                if (msg.IsAll != 1)
                {
                    return;
                }
                MainMenus = msg.MainMenus;
                System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    AllotPerPage = new AllotPermission(MainMenus);
                    DialogHost.Show(AllotPerPage, "MainPanel", ConfirmAllotPer);
                }));
            }
        }




        /// <summary>
        /// 获取角色列表
        /// </summary>
        public void GetRoles()
        {
            RequestRoleListReq msg = new RequestRoleListReq(MessageId.REQUEST_ROLE_LIST)
            {
                Page = CurrentPage,
                Limit = LIMIT,
                Condition = Condition
            };
            ApplicationClient.Instance().Send(msg);
        }


        /// <summary>
        /// 列表信息返回
        /// </summary>
        /// <param name="message">返回的消息</param>
        private void RolesResp(ResponseBaseMessage message)
        {
            if (message is RoleListResp msg)
            {
                Roles = msg.Roles;
                HasPrePage = CurrentPage > 1;
                HasNextPage = CurrentPage < (int)Math.Ceiling((double)msg.Count / LIMIT);
            }
        }




        /// <summary>
        /// 删除角色回复消息接收
        /// </summary>
        /// <param name="message">回复消息</param>
        private void ReceiveOptMsg(ResponseBaseMessage message)
        {
            if (message is OperationResp msg)
            {
                if (msg.Code == 200 && msg.OptType == (int)OptType.DELETE_ROLE)
                {
                    RoleService.Instance().RefreshRoles();
                    GetRoles();
                }
            }
        }


        private ViewRole condition = new ViewRole() { Status = 0 };

        public ViewRole Condition
        {
            get { return condition; }
            set
            {
                condition = value;
                RaisePropertyChanged("Condition");
            }
        }

        public DelegateCommand SearchCommand { get; set; }
        private void Search()
        {
            GetRoles();
        }

        public DelegateCommand ResetCommand { get; set; }
        private void Reset()
        {
            Condition.RoleName = string.Empty;
            Condition.Status = 0;
            GetRoles();
        }










    }


}
